package workquene;

import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;
import utils.RabbitMQUtils;

import java.io.IOException;

public class Customer1 {

    public static void main(String[] args) throws IOException {
        // 获取连接
        Connection connection = RabbitMQUtils.getConnection();
        final Channel channel = connection.createChannel();
        channel.basicQos(1);    // 每次只能消费一个消息

        channel.queueDeclare("work", true, false, false, null);

        // 参数1：队列名称
        // 参数2：消息自动确认，true-会自动确认消息，false-不会自动确认消息
//        channel.basicConsume("work", true, new DefaultConsumer(channel) {
        channel.basicConsume("work", false, new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("消费者-1：" + new String(body));
                // 手动确认
                channel.basicAck(envelope.getDeliveryTag(), false);
            }
        });
    }
}
